package com.kye.express.business.freight_rates_query;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.addrpicker.AddressPickerActivity;
import com.kye.addrpicker.model.AddressPickerResult;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.utils.DateUtils;
import com.kye.datetimepicker.DateTimePicker;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.databinding.ActivityMounthQueryBinding;
import com.kye.model.UserSession;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.freight_rates_query.QueryAreaByCustomerCodeResultBean;
import com.kye.model.bean.freight_rates_query.QueryBillingMethodResultBean;
import com.kye.model.bean.freight_rates_query.QueryCostResultBean;
import com.kye.model.bean.user.User;

import java.util.Date;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function3;
import io.reactivex.functions.Function5;

/**
 * 月结查询
 */
public class MounthQueryActivity extends BaseToolbarActivity implements MounthQueryActivityContract.MounthQueryActivityView {
    private static final int REQUEST_CODE_START = 001;
    private static final int REQUEST_CODE_END = 002;
    private ActivityMounthQueryBinding mBinding;
    private Context mContext;
    private MounthQueryActivityContract.MounthQueryActivityViewPresenter mPresenter;

    private String mStartAddressCode;//原寄地区号
    private String mEndAddressCode;//收件地区号
    private String mStartAddress;//原寄地
    private String mEndAddress;//寄件地
    private int mServicePosition;//寄件地
    private String mBillType;//记重方式
    private String mTime;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, MounthQueryActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_mounth_query);
        mPresenter = new MounthQueryActivityContract.MounthQueryActivityViewPresenter(this);
        mPresenter.bind(this);
        mContext = this;
        setUpToolbar((Toolbar) findViewById(R.id.toolbar));
        setTitle(getString(R.string.frq_mounth_query));
        initView();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        if (mPresenter != null) {
            mPresenter.unbind();
        }
        super.onDestroy();
    }

    private void initView() {
        if (UserSession.getInstance().getUser() != null) {
            mPresenter.queryArea(UserSession.getInstance().getUser().getCustomCode());
            String company = "";
            String customCode = UserSession.getInstance().getUser().getCustomCode();
            List<User.Address> addresses = UserSession.getInstance().getUser().getLastAddress();
            if (addresses != null && addresses.size() > 0 && (!TextUtils.isEmpty(customCode))) {
                for (User.Address item : addresses) {
                    if (customCode.equals(item.getCompanyCode())) {
                        company = item.getCompanyName();
                        break;
                    }
                }
            }
            mBinding.stvName.setCenterString(company);
        }
    }

    private void initEvent() {

        RxView.clicks(mBinding.stvStartAddress)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        AddressPickerActivity.startActivityForResult(MounthQueryActivity.this, getString(R.string.frq_start_address), AddressPickerActivity.Levels.city, REQUEST_CODE_START);
                    }
                });
        RxView.clicks(mBinding.stvEndAddress)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        AddressPickerActivity.startActivityForResult(MounthQueryActivity.this, getString(R.string.frq_end_address), AddressPickerActivity.Levels.city, REQUEST_CODE_END);
                    }
                });

        RxView.clicks(mBinding.stvTime)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        DateTimePicker.show(mContext, true, true, true, true, true, false, new DateTimePicker.DateTimeCallBack() {
                            @Override
                            public void callBack(Date date) {
                                mBinding.stvTime.setCenterTextColor(getResources().getColor(R.color.black_333));
                                mBinding.stvTime.setCenterString(DateUtils.getDateStringByDate(date));
                                mTime = DateUtils.getDateStringByDate(date);
                            }
                        });
                    }
                });
        RxView.clicks(mBinding.stvService)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        new MaterialDialog.Builder(mContext)
                                .items(getResources().getStringArray(R.array.frq_service_array))
                                .itemsCallback(new MaterialDialog.ListCallback() {
                                    @Override
                                    public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                                        mServicePosition = position;
                                        mBinding.stvService.setCenterTextColor(getResources().getColor(R.color.black_333));
                                        mBinding.stvService.setCenterString(text);
                                    }
                                })
                                .show();
                    }
                });

        Observable<CharSequence> startAddressChange = RxTextView.textChanges(mBinding.stvStartAddress.getCenterTextView()).cache();
        Observable<CharSequence> endAddressChange = RxTextView.textChanges(mBinding.stvEndAddress.getCenterTextView()).cache();
        Observable<CharSequence> serviceChange = RxTextView.textChanges(mBinding.stvService.getCenterTextView()).cache();
        Observable<CharSequence> weightChange = RxTextView.textChanges(mBinding.edtWeight).cache();
        Observable<CharSequence> timeChange = RxTextView.textChanges(mBinding.stvTime.getCenterTextView()).cache();


        Observable.combineLatest(startAddressChange, endAddressChange, serviceChange, new Function3<CharSequence, CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3) throws Exception {
                String hintString = getString(R.string.hint_select);
                return (!hintString.equals(charSequence)) && (!hintString.equals(charSequence2)) && (!hintString.equals(charSequence3));
            }
        })
                .compose(this.<Boolean>bindToLifecycleDestroy())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean && UserSession.getInstance().getUser() != null) {
                            mStartAddressCode = "";
                            mEndAddressCode = "";
                            mPresenter.queryBillingMethod(UserSession.getInstance().getUser().getCustomCode(), mStartAddress, mEndAddress, mServicePosition + "");
                        }
                    }
                });

        Observable.combineLatest(startAddressChange, endAddressChange, serviceChange, weightChange, timeChange, new Function5<CharSequence, CharSequence, CharSequence, CharSequence, CharSequence, Boolean>() {

            @Override
            public Boolean apply(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3, CharSequence charSequence4, CharSequence charSequence5) throws Exception {
                String hintString = getString(R.string.hint_select);
                return (!hintString.equals(charSequence)) && (!hintString.equals(charSequence2)) && (!hintString.equals(charSequence3)) && (!hintString.equals(charSequence5)) && charSequence4.length() > 0;
            }
        })
                .compose(this.<Boolean>bindToLifecycleDestroy())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        resetPrice();
                        mBinding.btnQuery.setEnabled(aBoolean);
                    }
                });

        RxView.clicks(mBinding.btnQuery)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (TextUtils.isEmpty(mStartAddressCode) || TextUtils.isEmpty(mEndAddressCode)) {
                            showNodatasDialog();
                            return;
                        }
                        if (UserSession.getInstance().getUser() != null) {
                            try {
                                int weight = Integer.valueOf(mBinding.edtWeight.getText().toString().trim());
                                mPresenter.queryCost(UserSession.getInstance().getUser().getCustomCode(), mStartAddressCode, mEndAddressCode, weight, weight, weight, mTime, mServicePosition);
                            } catch (Exception e) {

                            }
                        }
                    }
                });
    }

    private void resetPrice() {
        mBinding.tvPrice.setText("￥0.00");
        mBinding.tvPrice.setTextColor(getResources().getColor(R.color.black_999));
        mBinding.tvStartWeight.setText(getString(R.string.frq_mounth_price_tips));
    }

    private void setUpPrice(String price, String weight) {
        mBinding.tvPrice.setText("￥" + price);
        mBinding.tvPrice.setTextColor(getResources().getColor(R.color.frq_price_color));
        mBinding.tvStartWeight.setText(String.format(getString(R.string.frq_mounth_price_tips_two), weight));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            AddressPickerResult resultAddress = (AddressPickerResult) data.getSerializableExtra(AddressPickerActivity.KEY_ARG_PICKED_RESULT);
            if (resultAddress != null) {
                if (requestCode == REQUEST_CODE_START) {
                    String address = resultAddress.getProvince() + resultAddress.getCity();
                    mStartAddress = address;
                    mBinding.stvStartAddress.setCenterTextColor(getResources().getColor(R.color.black_333));
                    mBinding.stvStartAddress.setCenterString(address);

                } else if (requestCode == REQUEST_CODE_END) {
                    String address = resultAddress.getProvince() + resultAddress.getCity();
                    mEndAddress = address;
                    mBinding.stvEndAddress.setCenterTextColor(getResources().getColor(R.color.black_333));
                    mBinding.stvEndAddress.setCenterString(address);
                }
            }
        }
    }

    @Override
    public void onLoadedQueryArea(QueryAreaByCustomerCodeResultBean queryAreaByCustomerCodeResultBean) {
        if (queryAreaByCustomerCodeResultBean != null && queryAreaByCustomerCodeResultBean.getDatas() != null && queryAreaByCustomerCodeResultBean.getDatas().size() > 0) {
            mStartAddressCode = queryAreaByCustomerCodeResultBean.getDatas().get(0).getAreaNo();
            mStartAddress = queryAreaByCustomerCodeResultBean.getDatas().get(0).getAddressForShort();
            mBinding.stvStartAddress.setCenterTextColor(getResources().getColor(R.color.black_333));
            mBinding.stvStartAddress.setCenterString(mStartAddress);
        }
    }

    @Override
    public void onLoadedQueryBilling(QueryBillingMethodResultBean queryBillingMethodResultBean) {
        if (queryBillingMethodResultBean != null) {
            mStartAddressCode = queryBillingMethodResultBean.getSendAreaCode();
            mEndAddressCode = queryBillingMethodResultBean.getReceiptAreaCode();
            mBillType = queryBillingMethodResultBean.getBillType();
        }
    }

    @Override
    public void onLoaded(OpenApiResult<QueryCostResultBean> queryCostResult) {
        if (queryCostResult != null && queryCostResult.getData() != null) {
            setUpPrice(queryCostResult.getData().getMoney(), queryCostResult.getData().getWeight());
        }
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public void onLoading() {

    }

    private void showNodatasDialog() {
        new MaterialDialog.Builder(mContext)
                .content(R.string.frq_no_datas)
                .negativeText(getString(R.string.common_know))
                .show();
    }
}
